/*
 * Create:      柿子
 * CreateDate:  2023/03/28
 * Describe：   视光 - 生产厂家维护
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, message, Popconfirm, Icon, Radio, Checkbox, Badge, Spin } from 'antd';
import { Util, dayFormat } from 'tools';
import store from 'store';
import moment from 'moment';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import ReturnOrder from '../glassesManagement/component/ReturnOrder';
import SupplierAuditRecord from './component/SupplierAuditRecord';
import RangeDatePicker from 'components/rangePicker/index';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class OptometryManufacturerMaintenance extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      queryParams: {
        inputDesc: undefined,
        startDate: undefined,
        endDate: undefined,
        useFlag: true,
        status: '', // 审核状态
        statusType: undefined, // 审核类型
      },
      page: 1,
      pageSize: 20,
      loading: false,
      tableData: [],
      total: 0,
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      copyRowData: {},
      formData: [],
      saveLoading: false,
      productRowID: '',
      queryHeight: 78, // 查询栏高度
      categoryData: {},
      licenceData: [], // 许可证数据 - 默认至少存在一个
      licenceFormData: [], // 许可证表单数据
      otherFormData: [], // 其他信息
      detailLoading: false
    };
    this.queryRef = React.createRef();
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('OptometryManufacturerMaintenance', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('OptometryManufacturerMaintenance', false);
      }
    }
    // 界面类型 - create(制单) / reviewed(审核)
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log('OptometryManufacturerMaintenance', categoryData);
    this.setState({ categoryData }, () => {
      this.getTableColumns();
      this.getOtherTableColumns();
      this.getLicenceTableColumns('init');
    });
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  getSelectData = async () => {
    try {
      let { categoryData, queryParams } = this.state;
      let data = {
        params: [{
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
        }]
      }
      let res = await React.$asyncPost(this, '17060100', data);
      let selectData = res?.result || {};
      let status = selectData?.status || [];
      let activeStatusArr = status && status.filter(item => item.default === 'Y');
      queryParams.status = activeStatusArr && activeStatusArr.length > 0 ? activeStatusArr[0]?.id : ''; // 默认审核状态
      if (categoryData?.interfaceType === 'reviewed') { // 默认状态类型
        let statusType = selectData?.statusType || [];
        let activeStatusTypeArr = statusType && statusType.filter(item => item.default === 'Y');
        queryParams.statusType = activeStatusTypeArr && activeStatusTypeArr.length > 0 ? activeStatusTypeArr[0]?.id : '';
        // 默认日期
        queryParams.startDate = selectData?.startDate || moment().format(dayFormat);
        queryParams.endDate = selectData?.endDate || moment().format(dayFormat);
      }
      this.setState({ selectData, queryParams }, () => {
        this.getTableData();
        this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 78 });
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          compontName: categoryData?.interfaceType === 'reviewed' ? 'OptometryManufacturerMaintenanceAudit' : 'OptometryManufacturerMaintenance',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      let formData = res.result?.formData || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if ((item.dataIndex === 'statusDesc' && text === '停用') || (item.dataIndex === 'auditStatusDesc' && (text === '审核拒绝' || text === '拒绝审核' || text === '拒绝'))) { // 状态
                return (
                  <span className="common-record-delete-span">{text}</span>
                );
              } else {
                return text;
              }
            }
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        });
      }
      this.setState({ formData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getLicenceTableColumns = async (type) => {
    try {
      let data = {
        params: [{
          compontName: 'SupplierMaintenanceLicence',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let licenceFormData = res.result?.formData || [];
      this.setState({ licenceFormData }, () => {
        if (type === 'init') {
          this.getSelectData();
          this.handleLicenceAdd();
        }
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getOtherTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometryManufacturerMaintenanceOther',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let otherFormData = res.result?.formData || [];
      this.setState({ otherFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async (isReset) => {
    try {
      this.setState({ loading: true });
      const { queryParams, page, pageSize, categoryData } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag && categoryData?.interfaceType === 'create' ? 'Y' : 'N',
        }],
        pagination: [{
          pageSize,
          currentPage: page,
        }],
      }
      let res = await React.$asyncPost(this, '17060101', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ tableData, total: res.result?.total || 0, loading: false }, () => {
        isReset !== 'N' && this.handleReset();
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        isReset !== 'N' && this.handleReset();
      });
    }
  }

  // 操作行
  handleRowClick = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'manfID';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          this.setState({ rowID: record[idIndex] }, () => {
            this.queryRowDataByID();
          });
        } else {
          this.handleReset();
        }
      }
    }
  }

  // 根据行ID获取明细数据
  queryRowDataByID = async () => {
    try {
      this.setState({ detailLoading: true });
      const { categoryData, rowID, selectData } = this.state;
      const idIndex = categoryData?.idIndex || 'manfID';
      let data = {
        params: [{
          [idIndex]: rowID,
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
        }]
      }
      let res = await React.$asyncPost(this, '17060102', data);
      let rowData = res?.result || {};
      let copyRowData = JSON.parse(JSON.stringify(rowData));
      let licenceData = []; // 企业厂家用
      let licenceArr = this.getLicenceArr(rowData);
      if (licenceArr && licenceArr.length > 0) { // 不存在则默认返回一个
        for (let i = 0; i < licenceArr.length; i++) {
          let currentKey = i + 1;
          let currentFormData = this.filterLicenceFormData(currentKey, licenceArr[i]?.newLicenceTypeID || licenceArr[i]?.licenceTypeID || '');
          let currentLicenceRowData = this.filterLicenceValues(licenceArr[i], 'add', currentKey);
          licenceData.push({
            key: currentKey,
            licenceID: licenceArr[i]?.licenceID || '',
            deleteFlag: licenceArr[i]?.deleteFlag || '',
            rowData: currentLicenceRowData, // 可不存
            title: licenceArr[i]?.licenceTypeDesc || '许可证',
            formData: currentFormData
          });
          rowData = { ...rowData, ...currentLicenceRowData };
          this.state['licenceFormData' + currentKey] = currentFormData;
        }
      } else {
        let defaultFormData = this.filterLicenceFormData(1);
        licenceData = [{
          key: 1,
          formData: defaultFormData
        }];
        this.state['licenceFormData' + 1] = [...defaultFormData];
      }
      let updateObj = rowData?.updateObj?.modifyJson || {};
      let currentUpdateObj = {}; // 实际修改的数据
      // 提交修改和退回提交展示痕迹
      if (typeof (updateObj) === 'object' && JSON.stringify(updateObj) !== '{}' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
        let diffData = [], oldData = {}, newData = {};
        for (let keys in updateObj) {
          for (let rowKeys in rowData) {
            if (keys === rowKeys && String(updateObj[keys]) !== String(rowData[rowKeys])) {
              currentUpdateObj[keys] = updateObj[keys]
              let formDataDataIndex = this.getTheCorrespondingFromData(keys, licenceData);
              let formItemData = Util.returnDataCccordingToAttributes(this.state[formDataDataIndex], keys, 'dataIndex');
              let selectDataKey = formItemData?.className;
              let typeCode = formItemData?.typeCode;
              let title = typeCode === 'RangePicker' ? (formItemData?.dataIndex.indexOf(keys) === 0 ? (formItemData?.title + '【开始】') : (formItemData?.title + '【结束】')) : formItemData?.title;

              let newVal = typeCode === 'Select' ? (
                updateObj[keys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], updateObj[keys], 'id').descripts : (rowData?.updateObj[keys.replace('ID', 'Desc')] || '')
              ) : updateObj[keys];
              let oldVal = typeCode === 'Select' ? (
                rowData[rowKeys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], rowData[rowKeys], 'id').descripts : (rowData[keys.replace('ID', 'Desc')] || '')
              ) : rowData[rowKeys];
              newData[keys] = newVal;
              oldData[keys] = oldVal;
              diffData.push({
                typeCode,
                id: 'linkID_' + (typeCode === 'RangePicker' ? formItemData?.dataIndex : keys),
                dataIndex: keys,
                title,
                new: newVal,
                old: oldVal
              })
            }
          }
        }
        rowData = { ...rowData, ...updateObj }; // 界面展示修改后的值
        rowData.diffData = diffData;
      }
      this.setState({
        licenceData,
        rowData,
        copyRowData,
        detailLoading: false,
      }, () => {
        this.setColumnsLinkUrl('formData', currentUpdateObj);
        this.setColumnsLinkUrl('otherFormData', currentUpdateObj);
        for (let i = 0; i < licenceData.length; i++) {
          let currentKey = i + 1;
          if (licenceData[i]?.deleteFlag !== 'Y') {
            this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), currentUpdateObj);
          }
          setTimeout(() => {
            this['licenceRef' + currentKey] && this['licenceRef' + currentKey]?.handleDataTransformation();
          }, 100)
        }
      });
    } catch (error) {
      this.setState({ detailLoading: false });
    }
  }

  // 获取界面展示的许可证信息
  getLicenceArr = (rowData) => {
    const { categoryData } = this.state;
    let oldLicenceArr = rowData?.licenceArr || [];
    if (rowData.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
      let newLicenceArr = JSON.parse(JSON.stringify(rowData?.updateObj?.licenceArr || []));
      for (let i = 0; i < newLicenceArr.length; i++) {
        for (let j = 0; j < oldLicenceArr.length; j++) {
          if (newLicenceArr[i] && 'licenceID' in newLicenceArr[i] && oldLicenceArr[j] && 'licenceID' in oldLicenceArr[j] && (newLicenceArr[i].licenceID === oldLicenceArr[j].licenceID)) {
            newLicenceArr[i] = { ...newLicenceArr[i], ...oldLicenceArr[j], newLicenceTypeID: newLicenceArr[i]?.licenceTypeID || oldLicenceArr[j]?.licenceTypeID || '' }
          }
        }
      }
      return newLicenceArr;
    }
    return oldLicenceArr;
  }

  // 根据dataIndex获取对应的表头数据
  getTheCorrespondingFromData = (dataIndex, licenceData) => {
    let formFlag = '';
    formFlag = this.getFormDataFlag('formData', dataIndex);
    if (!formFlag) { // formFlag不存在时再去otherFormData中查找
      for (let i = 0; i < licenceData.length; i++) {
        let currentLicenceFormData = licenceData[i]?.formData || [];
        for (let j = 0; j < currentLicenceFormData.length; j++) {
          if ((currentLicenceFormData[j].dataIndex === dataIndex) || (currentLicenceFormData[j].dataIndex.indexOf('^') > -1 && currentLicenceFormData[j].dataIndex.indexOf(dataIndex) > -1)) {
            formFlag = 'licenceFormData' + (licenceData[i]?.key || (i + 1));
            break
          }
        }
      }
    }
    if (!formFlag) { // formFlag不存在时再去otherFormData中查找
      formFlag = this.getFormDataFlag('otherFormData', dataIndex);
    }
    return formFlag;
  }

  // 判断dataIndex属于那个formData
  getFormDataFlag = (formDataDataIndex, dataIndex) => {
    let currentFormDataDataIndex = '';
    let formData = this.state[formDataDataIndex];
    if (formData && Array.isArray(formData) && formData.length > 0) {
      for (var i = 0; i < formData.length; i++) {
        if ((formData[i].dataIndex === dataIndex) || (formData[i].dataIndex.indexOf('^') > -1 && formData[i].dataIndex.indexOf(dataIndex) > -1)) {
          currentFormDataDataIndex = formDataDataIndex;
          break;
        }
      }
    }
    return currentFormDataDataIndex;
  }

  setColumnsLinkUrl = (cloumnsIndex, updateObj) => {
    const { rowData, categoryData } = this.state;
    for (let i = 0; i < this.state[cloumnsIndex].length; i++) {
      let currentColumnsRecord = this.state[cloumnsIndex][i];
      this.state[cloumnsIndex][i].linkUrl = '';
      for (let updateKey in updateObj) {
        if (((currentColumnsRecord.dataIndex === updateKey) || (currentColumnsRecord?.typeCode === 'RangePicker' && (currentColumnsRecord.dataIndex.indexOf(updateKey) > -1))) && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
          this.state[cloumnsIndex][i].linkUrl = 'linkID_' + (currentColumnsRecord?.typeCode === 'RangePicker' ? currentColumnsRecord.dataIndex : updateKey);
          break;
        }
      }
    }
    this.setState({});
  }

  // 处理许可证表单数据
  filterLicenceFormData = (key = 1, licenceTypeID) => {
    let { licenceFormData, selectData } = this.state;
    let nLicenceFormData = Util.customDeepCopy(licenceFormData);
    for (let i = 0; i < nLicenceFormData.length; i++) {
      let currentDataIndex = nLicenceFormData[i].dataIndex;
      nLicenceFormData[i].dataIndex = currentDataIndex + '_' + key;
      if (currentDataIndex === 'licenceScope') { // 修改范围描述
        nLicenceFormData[i].title = +licenceTypeID === 1 ? '经营范围' : (+licenceTypeID === 5 ? '诊疗科目' : '生产范围');
      }
      if (currentDataIndex === 'licenceNo') {
        nLicenceFormData[i].title = +licenceTypeID === 5 ? '登记号' : '许可证编码';
      }
      if (currentDataIndex === 'endDate') { // 有效期至
        nLicenceFormData[i].title = +licenceTypeID === 5 ? '有效期限' : '有效期至';
        nLicenceFormData[i].typeCode = +licenceTypeID === 5 ? 'RangePicker' : 'Date';
        nLicenceFormData[i].dataIndex = +licenceTypeID === 5 ? ('stDate_' + key + '^endDate_' + key) : ('endDate_' + key);
      }
      if (currentDataIndex === 'licenceTypeID') { // 许可证类型
        // nLicenceFormData[i].defaultValue = '1';
        nLicenceFormData[i].detailItem = selectData?.licenceType || [];
        nLicenceFormData[i].callBackResult = 'Fn' + key;
        nLicenceFormData[i].changeCallBack = this.handleLicenceTypeChange;
      }
    }
    return nLicenceFormData;
  }

  // 选中行操作
  handleRowClassName = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'manfID';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 保存
  handleSave = Util.debounce(async (fn, statusCode) => {
    let { licenceData, rowID, rowData } = this.state;
    let baseInfoVal = await this.baseInfoRef.handleSave();
    if (baseInfoVal && baseInfoVal.error) {
      message.error(baseInfoVal?.errorMessage || '请先完善基本信息。');
      return;
    }
    let licenceArr = [];
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let licenceVal = await this['licenceRef' + currentKey].handleSave();
        if (licenceVal && licenceVal.error) {
          message.error('请先完善许可证相关信息。');
          return;
        } else {
          let currentLicenceID = 'licenceID_' + currentKey;
          licenceArr.push({ licenceID: rowData && currentLicenceID in rowData && rowData[currentLicenceID] ? rowData[currentLicenceID] : '', ...this.filterLicenceValues(licenceVal), error: undefined });
        }
      } else { // 删除的传入原值
        licenceArr.push({ ...this.filterLicenceValues(licenceData[i]?.rowData || {}), deleteFlag: 'Y' });
      }
    }
    let otherVal = await this.otherRef.handleSave();
    if (otherVal && otherVal.error) {
      message.error('请先完善其他信息。');
      return;
    }
    fn && fn(statusCode, {
      ...baseInfoVal,
      ...otherVal,
      manfID: rowID,
      licenceArr,
      baseArr: this.getBaseArr(),
    })
  })

  // 处理许可证数据
  filterLicenceValues = (licenceVal, type, key) => {
    let nLicenceVal = {};
    for (let keys in licenceVal) {
      if (type === 'add') {
        nLicenceVal[keys + '_' + key] = licenceVal[keys];
      } else {
        let currentKey = keys.indexOf('_') > -1 ? keys.split('_')[0] : keys;
        nLicenceVal[currentKey] = licenceVal[keys];
      }
    }
    return nLicenceVal;
  }

  // 基本信息保存 
  handleBaseInfoSave = async (statusCode, baseObj) => {
    try {
      this.setState({ saveLoading: true });
      let data = {
        params: [{
          status: statusCode,
          ...baseObj
        }]
      }
      let res = await React.$asyncPost(this, '17060103', data);
      message.success(res.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      this.getTableData();
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  // 判断表单信息是否修改
  isModifyForm = (returnType = '') => {
    let { rowData, licenceData } = this.state;
    let values = {};
    let baseValues = this.baseInfoRef && this.baseInfoRef.getFieldsValue('N');
    let licenceValues = {};
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let currentLicenceVal = (this['licenceRef' + currentKey] && this['licenceRef' + currentKey].getFieldsValue('N')) || {};
        licenceValues = { ...licenceValues, ...currentLicenceVal };
      }
    }
    let otherValues = this.otherRef && this.otherRef.getFieldsValue('N');
    values = { ...baseValues, ...licenceValues, ...otherValues };
    let isModify = Util.isModifyForm(values, rowData, returnType);
    return isModify;
  }

  // 修改库存项状态 - 拒绝时传入25，审核通过传入30
  handleModifyDataStatus = async (statusCode, baseObj = {}, compnentSource, remark) => {
    try {
      this.setState({ saveLoading: true });
      const { rowData, categoryData } = this.state;
      let modifyJson = {};
      if (categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25' || rowData?.modifyStatus === '30')) {
        let modifyForm = this.isModifyForm('obj');
        let oldModifyJson = rowData?.updateObj?.modifyJson || {};
        // 退回的时候需和历史修改的数据一并保存
        modifyJson = rowData?.modifyStatus === '25' ? { ...oldModifyJson, ...modifyForm } : { ...modifyForm };
      }
      let data = {
        params: [{
          manfID: rowData?.manfID || '',
          type: rowData?.auditStatus !== '30' ? 'INSERT' : 'UPDATE', // INSERT-新增时 / UPDATE-修改
          status: statusCode,
          remark: remark || undefined, // 拒绝备注
          updateValue: categoryData?.interfaceType === 'create' ? {
            ...baseObj,
            ...modifyJson,
            modifyJson, // 需要修改的数据 - 提交修改时传入
          } : {},
        }]
      }
      let res = await React.$asyncPost(this, '17060104', data);
      message.success(res?.errorMessage || '操作成功');
      this.setState({ saveLoading: false });
      this.returnOrderRef && this.returnOrderRef.modifyVisible(false, '', '', 'Y');
      this.getTableData();
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  getBaseArr = () => {
    const { rowData, formData, licenceData, otherFormData } = this.state;
    let nRowData = JSON.parse(JSON.stringify(rowData));
    if (!(nRowData && 'manfID' in nRowData && nRowData.manfID)) { // 另存清空对比数据
      nRowData = {};
    }
    let baseValues = this.baseInfoRef && this.baseInfoRef.getFieldsValue('N');
    let baseDiffData = Util.getDiffData(baseValues, nRowData, formData);
    let licenceDiffData = [];
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let currentLicenceVal = this['licenceRef' + currentKey] && this['licenceRef' + currentKey].getFieldsValue('N') || {};
        let currentLicenceDiffData = Util.getDiffData(currentLicenceVal, nRowData, licenceData[i]?.formData);
        licenceDiffData = [...licenceDiffData, ...currentLicenceDiffData];
      }
    }
    let otherValues = this.otherRef && this.otherRef.getFieldsValue('N');
    let otherDiffData = Util.getDiffData(otherValues, nRowData, otherFormData);
    return [...baseDiffData, ...licenceDiffData, ...otherDiffData];
  }

  // 基本信息重置
  handleReset = () => {
    let { licenceData } = this.state;
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), {});
      }
    }
    this.setColumnsLinkUrl('formData', {});
    this.setColumnsLinkUrl('otherFormData', {});
    this.baseInfoRef && this.baseInfoRef.resetFields();
    this.otherRef && this.otherRef.resetFields();
    this.setState({ rowID: '', rowData: {}, licenceData: [] }, () => {
      this.handleLicenceAdd();
    });
  }

  // 录入顺序
  handleEntrySequence = (componentName) => {
    this.baseInfoRef && this.baseInfoRef.showFromMaintenanceModal(componentName);
  }

  // 退回
  handleReturn = () => {
    this.returnOrderRef && this.returnOrderRef.modifyVisible(true, {}, '25');
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'manfID' || dataIndex === 'statusType' || dataIndex === 'status' || dataIndex === 'useFlag') {
        this.handleQuery();
      }
    })
  }

  // 查看审核记录
  handleAuditRecord = (record, e) => {
    React.$stopPropagation(e);
    this.auditRecordRef && this.auditRecordRef.modifyVisible(true, record);
  }

  // 新增许可证
  handleLicenceAdd = () => {
    let { licenceData } = this.state;
    let key = licenceData && licenceData.length > 0 ? licenceData.length + 1 : 1;
    let formData = this.filterLicenceFormData(key);
    this.state['licenceFormData' + key] = [...formData];
    licenceData.push({ key, formData });
    this.setState({ licenceData });
  }

  // 许可证类型切换
  handleLicenceTypeChange = (e, dataIndex, record) => {
    let { licenceData } = this.state;
    let callBackResult = (record?.callBackResult || 'Fn1').replace('Fn', '');
    let currentIndex = callBackResult - 1;
    if (licenceData && licenceData.length > currentIndex) {
      licenceData[currentIndex].title = record['licenceTypeDesc_' + callBackResult] || '';
      let currentFormData = licenceData[currentIndex]?.formData || [];
      // 修改范围描述
      for (let i = 0; i < currentFormData.length; i++) {
        if (currentFormData[i].code === 'licenceScope') { // 生产范围
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 1 ? '经营范围' : +record['licenceTypeID_' + callBackResult] === 5 ? '诊疗科目' : '生产范围';
        }
        if (currentFormData[i].code === 'licenceNo') { // 许可证编号
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 5 ? '登记号' : '许可证编码';
        }
        if (currentFormData[i].code === 'endDate') { // 有效期至
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 5 ? '有效期限' : '有效期至';
          licenceData[currentIndex].formData[i].typeCode = +record['licenceTypeID_' + callBackResult] === 5 ? 'RangePicker' : 'Date';
          licenceData[currentIndex].formData[i].dataIndex = +record['licenceTypeID_' + callBackResult] === 5 ? ('stDate_' + callBackResult + '^endDate_' + callBackResult) : ('endDate_' + callBackResult);
        }
      }
    }
    this.setState({ licenceData }, () => {
      this['licenceRef' + callBackResult] && this['licenceRef' + callBackResult].setFieldsValue({ [dataIndex]: record[dataIndex] }); // 解决第一次赋值异常
    });
  }

  // 删除许可证
  handleLicenceDelete = (index, record, isRevert) => {
    let { licenceData } = this.state;
    if (record && record.licenceID) {
      licenceData[index].deleteFlag = isRevert === 'revert' ? '' : 'Y';
    } else {
      licenceData = licenceData.filter(item => item.key !== record.key);
    }
    console.log("licenceData", licenceData)
    this.setState({ licenceData });
  }

  // 还原修改
  handleCancelModify = () => {
    let { copyRowData, licenceData } = this.state;
    let rowData = copyRowData;
    rowData.cancelModifyFlag = 'Y';
    let licenceArr = rowData?.licenceArr || [];
    if (licenceArr && licenceArr.length > 0) { // 不存在则默认返回一个
      for (let i = 0; i < licenceArr.length; i++) {
        let currentKey = i + 1;
        let currentFormData = this.filterLicenceFormData(currentKey, licenceArr[i]?.licenceTypeID || '');
        let currentLicenceRowData = this.filterLicenceValues(licenceArr[i], 'add', currentKey);
        licenceData.push({
          key: currentKey,
          licenceID: licenceArr[i]?.licenceID || '',
          deleteFlag: licenceArr[i]?.deleteFlag || '',
          rowData: currentLicenceRowData, // 可不存
          title: licenceArr[i]?.licenceTypeDesc || '许可证',
          formData: currentFormData
        });
        rowData = { ...rowData, ...currentLicenceRowData };
        this.state['licenceFormData' + currentKey] = currentFormData;
      }
    }
    this.setState({ rowData, licenceArr }, () => {
      for (let i = 0; i < licenceData.length; i++) {
        if (licenceData[i]?.deleteFlag !== 'Y') {
          this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), {});
        }
      }
      this.setColumnsLinkUrl('formData', {});
      this.setColumnsLinkUrl('otherFormData', {});
    });
  }

  render() {
    const { selectData, page, loading, tableData, total, totalWidth, columns, rowData, formData, saveLoading, queryParams, rowID, queryHeight, categoryData, otherFormData, licenceData,
      detailLoading
    } = this.state;
    const operationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span className="span" onClick={(e) => this.handleAuditRecord(record, e)}>
          {record?.tip === 'Y' ? (
            <Badge dot>
              审核记录
            </Badge>
          ) : '审核记录'}
        </span>
      ),
    };
    return (
      <div className="optometry-manufacturer-maintenance">
        <Row className="table-body-height">
          <Col span={10} className="common-col">
            <div style={{ paddingRight: '8px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    {categoryData?.interfaceType === 'reviewed' ? '厂家单据审核' : '厂家列表'}
                  </div>
                )}
                extra={(
                  categoryData?.interfaceType === 'reviewed' ? '' : <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示启用</Checkbox>
                )}
              >
                <div ref={this.queryRef}>
                  <div className="flex-align-items">
                    {categoryData?.interfaceType === 'reviewed' ? (
                      <>
                        <div className="flex-align-items" style={{ marginRight: '15px' }}>
                          <span className="common-input-label">日期：</span>
                          <RangeDatePicker
                            width="300px"
                            format="YYYY-MM-DD"
                            isChange={true}
                            endDate={queryParams?.endDate || undefined}
                            startDate={queryParams?.startDate || undefined}
                            endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                            startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                          />
                        </div>
                      </>
                    ) : ''}
                    <span className="common-input-label">厂家信息：</span>
                    <Input
                      value={queryParams?.inputDesc || undefined}
                      style={{ width: categoryData?.interfaceType === 'reviewed' ? '150px' : '250px' }}
                      placeholder="输入代码/名称查询"
                      className="common-query-input"
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'inputDesc')}
                      onPressEnter={this.handleQuery}
                    />
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  </div>
                  <div style={{ marginTop: '12px', display: categoryData?.interfaceType === 'reviewed' ? 'block' : 'none' }}>
                    <span className="common-input-label">审核类型：</span>
                    <Radio.Group value={queryParams?.statusType} onChange={(e) => this.handleModifyInputValue(e.target.value, 'statusType')}>
                      {selectData && 'statusType' in selectData && Array.isArray(selectData.statusType) && selectData.statusType.map((item, index) => {
                        return (
                          <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                        )
                      })}
                    </Radio.Group>
                  </div>
                  <div style={{ margin: '12px 0' }}>
                    <span className="common-input-label">审核状态：</span>
                    <Radio.Group value={queryParams?.status} onChange={e => this.handleModifyInputValue(e.target.value, 'status')}>
                      {selectData && 'status' in selectData && Array.isArray(selectData.status) && selectData.status.map((item, index) => {
                        return (
                          <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                        )
                      })}
                    </Radio.Group>
                  </div>
                </div>
                <PublicTablePagination
                  param={{
                    page,
                    total,
                    pageSize: '20',
                    loading: loading,
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    componentName: categoryData?.interfaceType === 'reviewed' ? 'OptometryManufacturerMaintenanceAudit' : 'OptometryManufacturerMaintenance',
                    y: store.getState().tableHeight.y + 75 - queryHeight,
                    height: store.getState().tableHeight.y + 125 - queryHeight + 'px',
                    columns: categoryData?.interfaceType === 'reviewed' ? columns : [...columns, operationObj], // 表头配置
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.handleRowClick}
                  setRowClassNamePublic={this.handleRowClassName}
                />
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={14} className="common-col common-right-col">
            <Card
              size="small"
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  {(categoryData?.interfaceType === 'reviewed' && rowData?.auditStatus === '30' && rowData?.modifyStatus === '20') || (categoryData?.interfaceType === 'create' && (rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')) ? (
                    categoryData?.interfaceType === 'create' ? (
                      <span>【{rowData?.manfDesc || ''}】已提交审核，请耐心等待。</span>
                    ) : (
                      <span>您可以点击下划线上的文字查看修改前的数据</span>
                    )
                  ) : (
                    <div className="flex">
                      {'正在' + (rowID ? (categoryData?.interfaceType === 'reviewed' ? '查看' : '修改') : '添加') + '厂家信息'}
                      <span
                        title={rowData?.remark || ''}
                        className="common-record-delete-span ellipsis"
                        style={{
                          display: (rowData?.auditStatus === '25' || rowData?.modifyStatus === '25') ? 'inline-block' : 'none',
                          maxWidth: '36vw'
                        }}
                      >
                        【退回原因：{rowData?.remark || ''}】
                      </span>
                    </div>
                  )}
                </div>
              )}
              bordered={false}
              bodyStyle={{ padding: 0 }}
              extra={(
                categoryData?.interfaceType === 'create' ? (
                  <Button
                    icon="plus"
                    size="small"
                    className="add-btn add-btn-nohover"
                    onClick={this.handleReset}
                  >
                    新增厂家
                  </Button>
                ) : ''
              )}
            >
              <Spin spinning={detailLoading} tip="数据加载中……">
                <div style={{ height: store.getState().tableHeight.y + 200 + 'px', padding: '12px 6px 56px 12px' }}>
                  <div className="scroll-bar-style" style={{ paddingRight: '6px', overflow: 'auto', height: '100%' }}>
                    <Card
                      type="inner"
                      size="small"
                      title="营业执照"
                      bordered={false}
                      bodyStyle={{ paddingBottom: 0 }}
                      extra={(
                        categoryData?.entrySequenceBtnFlag === 'Y' ? (
                          <Button
                            size="small"
                            onClick={() => this.handleEntrySequence('OptometryManufacturerMaintenance')}
                          >
                            录入顺序
                          </Button>
                        ) : ''
                      )}
                    >
                      <DynamicRenderingForm
                        isEnterJump='Y'
                        rowData={rowData}
                        formData={formData}
                        selectData={selectData}
                        handleQueryFormData={this.getTableColumns}
                        onRef={ref => this.baseInfoRef = ref}
                      />
                    </Card>
                    <Card
                      type="inner"
                      size="small"
                      title="许可证"
                      bordered={false}
                      bodyStyle={{ padding: '6px 0' }}
                      extra={(
                        <>
                          {categoryData?.interfaceType === 'create' && rowData?.auditStatus !== '20' && rowData?.modifyStatus !== '20' ? (
                            <Button
                              icon="plus"
                              size="small"
                              type="link"
                              onClick={this.handleLicenceAdd}
                            >
                              新增许可证
                            </Button>
                          ) : ''}
                          {categoryData?.entrySequenceBtnFlag === 'Y' ? (
                            <Button
                              size="small"
                              style={{ marginLeft: '12px' }}
                              onClick={() => this.handleEntrySequence('SupplierMaintenanceLicence')}
                            >
                              录入顺序
                            </Button>
                          ) : ''}
                        </>
                      )}
                    >
                      {licenceData && Array.isArray(licenceData) && licenceData.map((item, index) => {
                        return (
                          <div
                            key={index}
                            className="sm-licence-item"
                            style={{
                              borderBottom: licenceData.length === 1 || (licenceData.length > 1 && index === licenceData.length - 1) ? '' : '1px solid #e8e8e8',
                              paddingTop: licenceData.length === 1 ? '12px' : 0,
                              background: item?.deleteFlag === 'Y' ? '#f3f3f352' : !(item?.licenceID) ? '#f5fffc63' : '#fff'
                            }}>
                            <div style={{ display: licenceData && licenceData.length > 1 ? 'flex' : 'none' }} className="flex-between-center">
                              <div className="card-title-left-icon sm-card-title">
                                <div></div>
                                <div>
                                  <span style={{ textDecoration: item?.deleteFlag === 'Y' ? 'line-through' : '' }}>
                                    {item?.title || ('许可证' + (item?.key || (index + 1)))}
                                  </span>
                                  {rowData?.auditStatus !== '30' ? '' : (item?.deleteFlag === 'Y' ? <span className="common-record-delete-span">【本次删除】</span> : (!(item?.licenceID) ? <span style={{ color: '#19cf9e' }}>【本次添加】</span> : ''))}
                                </div>
                              </div>
                              {index === 0 || categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? '' : (
                                item?.deleteFlag === 'Y' ? (
                                  categoryData?.revertFlag !== 'N' ? (
                                    <span className="span" onClick={() => this.handleLicenceDelete(index, item, 'revert')}>
                                      还原
                                    </span>
                                  ) : ''
                                ) : (
                                  <Popconfirm placement="topRight" title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleLicenceDelete(index, item)}>
                                    <span className="span common-record-delete-span">
                                      <Icon type="delete" style={{ marginRigth: '2px' }} />
                                      删除
                                    </span>
                                  </Popconfirm>
                                )
                              )}
                            </div>
                            <DynamicRenderingForm
                              isEnterJump='Y'
                              rowData={rowData}
                              formData={this.state['licenceFormData' + item.key] || []}
                              selectData={selectData}
                              handleQueryFormData={this.getLicenceTableColumns}
                              onRef={ref => this['licenceRef' + item.key] = ref}
                            />
                          </div>
                        )
                      })}
                    </Card>
                    <Card
                      type="inner"
                      size="small"
                      title="其他信息"
                      bordered={false}
                      bodyStyle={{ paddingBottom: 0 }}
                      extra={(
                        categoryData?.entrySequenceBtnFlag === 'Y' ? (
                          <Button
                            size="small"
                            onClick={() => this.handleEntrySequence('OptometryManufacturerMaintenanceOther')}
                          >
                            录入顺序
                          </Button>
                        ) : ''
                      )}
                    >
                      <DynamicRenderingForm
                        isEnterJump='Y'
                        rowData={rowData}
                        formData={otherFormData}
                        selectData={selectData}
                        handleQueryFormData={this.getOtherTableColumns}
                        onRef={ref => this.otherRef = ref}
                      />
                    </Card>
                  </div>
                </div>
              </Spin>
            </Card>
            <div className="sm-base-info-footer">
              {categoryData?.interfaceType === 'reviewed' ? ( // 审核
                <>
                  {rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                    <Popconfirm
                      title="确定要退回吗?"
                      onConfirm={this.handleReturn}
                    >
                      <Button
                        ghost
                        type="danger"
                      >
                        审核不通过
                      </Button>
                    </Popconfirm>
                  ) : (
                    <Button
                      type="danger"
                      disabled
                    >
                      审核不通过
                    </Button>
                  )}
                  <Button
                    type="primary"
                    loading={saveLoading}
                    style={{ marginLeft: '12px' }}
                    disabled={!(rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')}
                    onClick={() => this.handleModifyDataStatus('30')}
                  >
                    {saveLoading ? '审核中…' : '审核通过'}
                  </Button>
                </>
              ) : (
                <>
                  {categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && rowData?.modifyStatus === '25' ? (
                    rowData?.cancelModifyFlag === 'Y' ? (
                      <Button
                        ghost
                        type="danger"
                        disabled
                        style={{ marginRight: '12px' }}
                      >
                        放弃变更
                      </Button>
                    ) : (
                      <Popconfirm
                        title="放弃变更后不可恢复，确定要放弃吗?"
                        onConfirm={this.handleCancelModify}
                      >
                        <Button
                          ghost
                          type="danger"
                          style={{ marginRight: '12px' }}
                        >
                          放弃变更
                        </Button>
                      </Popconfirm>
                    )
                  ) : ''}
                  <Button
                    type="primary"
                    loading={saveLoading}
                    disabled={!(!rowID || rowData?.auditStatus === '' || rowData?.auditStatus === '10' || rowData?.auditStatus === '25' || (rowData?.auditStatus === '30' && (rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25' || rowData?.modifyStatus === '30')))}
                    onClick={rowData?.auditStatus !== '30' ? () => this.handleSave(this.handleBaseInfoSave, '20') : () => this.handleSave(this.handleModifyDataStatus, '20')}
                  >
                    {saveLoading ? '提交中…' : ((rowData?.auditStatus === '25' || rowData?.modifyStatus === '25') && rowData?.cancelModifyFlag !== 'Y' ? '重新提交' : (rowData?.auditStatus === '30' ? '提交修改' : '提交审核'))}
                  </Button>
                </>
              )}
            </div>
          </Col>
        </Row>

        {/* 审核记录 */}
        <SupplierAuditRecord
          auditTableCode="17060105"
          detailCode="17060106"
          propsRowIDIndex="manfID"
          statusFlagIndex=""
          rowIDDataIndex="optManfRecordID"
          interfaceType="OptometryManufacturerMaintenance"
          detailTableDataIndex=""
          tabList={[{
            key: '1',
            tab: '基本信息',
          }]}
          onRef={ref => this.auditRecordRef = ref}
        />

        {/* 退回订单 */}
        <ReturnOrder modalTitle="退回" selectData={{}} modifyApplicationFormStatus={this.handleModifyDataStatus} onRef={ref => this.returnOrderRef = ref} />
      </div>
    )
  }
};

export default OptometryManufacturerMaintenance;